<?php
function dmodel_new_object($query,$data=array()) {
	$a = dmodel_get_args($query,"class");	
	$c = dmodel_get_class($a->class);	
	$p = dmodel_get_prefix($a);

	$d = new stdClass();
	$d->form = $a->class;
	$d->mood = 1;
	$d->born = date("Y-m-d H:i:s");
	$d->uniq = isset($a->uniq) ? $a->uniq : md5(rand(1000,9999).time());
	
	if (!dmodel_hit_object("{$d->form}&uniq={$d->uniq}")) {
		foreach($c->form as $f) {
			if (false) {
			} else if (dmodel_is_object_standard_field($f["class"])) {			
				$d->{$f["class"]} = $data[$f["field"]];
			} else if (dmodel_is_meta($f["class"])) {
			
			} else if (dmodel_is_object($f["class"])) {
			
			}
		}
		
		$i = dmodel_sql_insert($d,"object");
		$q = "INSERT INTO {$p}object({$i->fields}) VALUES ({$i->values})";
		$r = dmodel_query($q,"lastid");	
		return $r;	
	}
}

function dmodel_get_object($query,$data=array()) {
	$a = dmodel_get_args($query,"class");	
	$p = dmodel_get_prefix($a);

	#oh_dump($c);
	if ($a->get=="default") {
		return dmodel_get_object_default($query);
	}
	if ($a->get=="model") {
		oh_dump("AAA");
		return "";
	}	
	
	$w[] = "mood>0";
	$w[] = $a->class ? "form LIKE '{$a->class}'" : "form!=''";
	$w[] = isset($a->id) ? "id={$a->id}" : "id>0";
	$w = implode(" AND ",$w);
		
	$q = "SELECT * FROM {$p}object WHERE {$w} ";
	//oh_dump($q);
	if (isset($a->id)) {
		$r = dmodel_query($q,"record");
		$r = dmodel_object_decoration($r);
		$r = dmodel_object_meta_decoration($r);
		return $r;
	} else {
		$r = dmodel_query($q,"resultset");
		foreach($r as &$i) {
			$i = dmodel_object_decoration($i);
			$i = dmodel_object_meta_decoration($i);
		}
		return $r;
	}	
}

function dmodel_hit_object($query,$data=array()) {
	$a = dmodel_get_args($query,"class");	
	$c = dmodel_get_class($a->class);	
	$p = dmodel_get_prefix($a);

	$d = new stdClass();
	$d->form = $a->class;
	$d->uniq = $a->uniq;
	
	$q = "SELECT * FROM {$p}object WHERE form='{$d->form}' AND uniq='{$d->uniq}' LIMIT 1";
	
	$r = dmodel_query($q);	
	return $r;
}

function dmodel_object_decoration($r) {
	$c = dmodel_get_class($r->form);
	foreach($c->form as $i) {
		$r->{$i["field"]} = isset($r->{$i["class"]}) ? $r->{$i["class"]} : "";
	}
	return $r;
}

function dmodel_object_meta_decoration($r) {
	return $r;
}

function dmodel_get_object_default($query) {
	$a = dmodel_get_args($query,"class");	
	$c = dmodel_get_class($a->class);
	$p = dmodel_get_prefix($a);
	$q = "SHOW COLUMNS FROM {$p}object";
	$r = dmodel_query($q);	
	
	$d = new stdClass();
	
	foreach($r as $f) {
		$d->{$f->Field} = "";
	}
	
	foreach($c->form as $i) {		
		$d->{$i["field"]} = isset($d->{$i["class"]}) ? $d->{$i["class"]} : "";
	}
	
	return $d;
}